<template>
  <el-upload
    v-bind="$attrs"
    ref="upload_instructionsForUseFileList"
    class="upload-demo"
    :action="url"
    :limit="props.limit"
    :accept="accept"
    multiple
    :file-list="props.fileList"
    :before-upload="beforeAvatarUpload"
    :on-success="handleSuccess"
    :on-preview="handlePreview"
    :before-remove="beforeRemove"
    :on-remove="handleRemove"
    :on-exceed="onExceed"
  >
    <template v-if="!props.disabled && $attrs.drag">
      <slot name="dragContent">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </slot>
    </template>
    <el-button v-if="!props.disabled && !$attrs.drag" size="small" icon="el-icon-upload2">上传附件</el-button>

    <div v-if="!props.disabled" slot="tip" class="el-upload__tip">
      <div v-html="props.tip"></div>
      <div v-if="!!props.fileSize">
        文件大小不超过{{ fileSize + sizeUnit }}
        <!-- 当前文件大小：{{ (sumFileSize / sizeMap[sizeUnit]).toFixed(14) + sizeUnit }} -->
      </div>
    </div>
  </el-upload>
</template>

<script setup>
// import { download } from '@/api/resource-management'
// import { fileDownload } from '@/utils/download.js'
import { watch, ref } from 'vue'
import { MessageBox, Message } from 'element-ui'

const props = defineProps({
  fileList: {
    type: Array,
    required: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  tip: {
    type: String,
    default: ''
  },
  fileSize: {
    type: Number,
    default: 0
  },
  sizeUnit: {
    type: String,
    default: 'MB'
  },
  limit: {
    type: Number,
    default: 100
  },
  accept: {
    type: String,
    default: ''
  }
})
const sumFileSize = ref(0)

watch(
  () => props.fileList,
  () => {
    sumFileSize.value = props.fileList.reduce((pre, item) => pre + item.fileSize, 0)
  },
  { deep: true, immediate: true }
)
const emits = defineEmits(['input'])
const url = process.env.VUE_APP_BASE_API + 'files/upload'
const handleSuccess = (response, file) => {
  // console.log(response, file)
  if (response.success) {
    if (response.data.name) {
      const index = props.fileList.findIndex((item) => {
        const fileName = item.name ?? item.response?.name
        const responseFilename = file.response.data.name
        return fileName === responseFilename
      })
      if (index === -1) {
        props.fileList.push({ ...file.response.data, fileSize: file.size })
      } else {
        props.fileList.splice(index, 1, { ...file.response.data, fileSize: file.size })
      }
      emits('input')
    } else {
      Message.error(response.data.message)
      props.fileList.pop()
      emits('input')
    }
  }
}

const beforeAvatarUpload = (file) => {
  var suffix = file.name.substring(file.name.lastIndexOf('.')) // .txt
  if (props.accept === '' || props.accept.split(',').includes(suffix)) {
    const sizeMap = {
      KB: 1024,
      MB: 1024 * 1024,
      GB: 1024 * 1024 * 1024
    }
    const { fileSize, sizeUnit } = props
    if (!fileSize) {
      return true
    }
    const isInSize = file.size < fileSize * sizeMap[sizeUnit] - sumFileSize.value
    if (!isInSize) {
      Message.error(
        `上传失败！已上传文件大小${(sumFileSize.value / sizeMap[sizeUnit]).toFixed(3) + sizeUnit},
      ，还能上传 ${(fileSize - sumFileSize.value / sizeMap[sizeUnit]).toFixed(3) + sizeUnit}!`
      )
    }
    return isInSize
  } else {
    Message.error('上传文件不符合格式,请上传' + props.accept + '格式文件!')
    return false
  }
}

const handlePreview = (file) => {
  // const path = file.url ?? file.response?.url
  // const fileName = file.name ?? file.response?.name
  // download({ files: [{ path, fileName }] }).then((res) => {
  //   fileDownload(res)
  // })
}
const beforeRemove = (file, fileList) => {
  if (props.disabled) {
    Message.error('查看状态不可删除文件')
    return false
  }
  if (file.status === 'ready') {
    return true
  } else {
    return MessageBox.confirm(`确定移除 ${file.name}？`)
  }
}
const handleRemove = (file, fileList) => {
  const index = props.fileList.findIndex((item) => {
    const fileName = item.name ?? item.response?.name
    const delFileName = file.name ?? file.response?.name
    return fileName === delFileName
  })
  if (index !== -1) {
    props.fileList.splice(index, 1)
  }
}
const onExceed = () => {
  Message.error(`超过最大文件上传数量,最多能上传${props.limit}个！`)
}
</script>

<style lang="less" scoped></style>
